<#import "function.ftl" as func>
<#assign package=model.variables.package>
<#assign class=model.variables.class>
<#assign classVar=model.variables.classVar>
<#assign comment=model.tabComment>
<#assign system=vars.system>
<#assign domain=vars.domain>
<#assign sub=model.sub>
<#assign foreignKey=func.convertUnderLine(model.foreignKey)>
<#assign pkType=func.getPkType(model)>
<#assign fkType=func.getFkType(model)>
package ${domain}.${system}.dao.Impl;

import com.swh.${system}.dao.BaseDao;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Map;


import ${domain}.${system}.entity.${class};



import java.util.List;
import java.util.Map;


/**
* @Description ${comment} 数据访问接口
* @date ${date?string("yyyy-MM-dd HH:mm:ss")}
*/

public class BaseDaoImpl<T> extends SimpleJpaRepository<T,String>implements BaseDao<T> {


        //实体管理类，对持久化实体做增删改查，自动义sq操作模板所需要的核心类
        public final EntityManager entityManager;


        public BaseDaoImpl(JpaEntityInformation<T, String> entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityManager = entityManager;
        }

        @Override
        public List<Map> findAllByParams(String sql, Object... args) {
            //获取session
            Session session = (Session) entityManager.getDelegate();
            org.hibernate.Query q = session.createSQLQuery(sql);//这个方法就是自己执行开发者 传入的 自定义sql语句
            //查询结果转map
            q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
            int i = 0;
            for (Object arg : args) {
            q.setParameter(++i, arg);
            }
            return q.list();
            }

            @Override
            public Page<Map> findPageByParams(String sql, Pageable pageable, Object... args) {
                Session session = (Session) entityManager.getDelegate();
                org.hibernate.Query q = session.createSQLQuery(sql);
                q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                int i = 0;
                for (Object arg : args
                ) {
                q.setParameter(++i, arg);
                }

                List<Map> totalCount = q.list();
                    q.setFirstResult(pageable.getPageSize() * (pageable.getPageNumber()));
                    q.setMaxResults(pageable.getPageSize());
                    List<Map> pageCount = q.list();
                        Page<Map> pages = new PageImpl<>(pageCount, pageable, totalCount.size());
                            return pages;
   }

 }